<?php 
$code = $_GET['code'];
$state = $_GET['state'] ?: 123;
$APPID = "wx92e23e5b5cfee7c3";
$APPSECRET = '1ea79b1c73391dde3b60200a2e7518e8';
if(empty($code)){
    // $redirect_uri = encodeURIComponent($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    // $redirect_uri = urlencode( 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    // header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid={$APPID}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}&connect_redirect=1#wechat_redirect");
    return;
}

$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$APPID.'&secret='.$APPSECRET.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
    echo '<h1>错误：</h1>'.$token->errcode;
    echo '<br/><h2>错误信息：</h2>'.$token->errmsg;
    exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$APPID.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
    echo '<h1>错误：</h1>'.$access_token->errcode;
    echo '<br/><h2>错误信息：</h2>'.$access_token->errmsg;
    exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
    echo '<h1>错误：</h1>'.$user_info->errcode;
    echo '<br/><h2>错误信息：</h2>'.$user_info->errmsg;
    exit;
}
// 打印用户信息
echo '<pre>';
print_r($user_info);
echo '</pre>';
// print_r(urldecode($state));
header("location:" . urldecode($state));